package net.wanho.commons.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import net.wanho.commons.exception.ServiceException;
import net.wanho.commons.factory.BeanFactory;
import net.wanho.commons.transaction.TransManager;
import net.wanho.commons.util.JDBCUtil;

public class TransactionProxy {
	private static TransManager transManager = BeanFactory.getBean(TransManager.class);

	// 被代理类
	public static Object createProxy(final Object target) {
		// 通过JDK创建的动态代理
		Object proxyObject = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
				new InvocationHandler() {

					@Override
					public Object invoke(Object proxy, Method method,Object[] args) throws Throwable {
						Object res = null;
						try {
							transManager.beginTrans();
							res = method.invoke(target, args);
							transManager.commitTrans();
						} catch (InvocationTargetException e) {
							transManager.rollbackTrans();
							throw e.getTargetException() ;
						}finally {
							JDBCUtil.close();
						}
						return res;
					}
				});
		return proxyObject;
	}

}
